package com.zensun.system.service.impl;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zensun.common.constant.Constants;
import com.zensun.common.constant.UserConstants;
import com.zensun.common.utils.Assert;
import com.zensun.system.domain.SysMenu;
import com.zensun.system.domain.SysRoleMenu;
import com.zensun.system.domain.dto.SysMenuDto;
import com.zensun.system.domain.vo.*;
import com.zensun.system.mapper.SysMenuMapper;
import com.zensun.system.mapper.SysRoleMenuMapper;
import com.zensun.system.service.ISysMenuService;
import com.zensun.system.util.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 菜单 业务层处理
 *
 * @author gmk
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {
    public static final String PREMISSION_STRING = "perms[\"{0}\"]";

    @Autowired
    private SysMenuMapper menuMapper;

    @Autowired
    private SysRoleMenuMapper roleMenuMapper;

    @Override
    public List<SysMenuTreeListVo> selectMenuTreeList(SysMenuDto menuDto) {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        Set<Long> longs = SecurityUtils.isAdmin(userId) ? null : menuMapper.selectMenuIdsByUserId(userId);
        if (!CollUtil.isEmpty(longs)) {
            List<Long> menuIds = new ArrayList<>(longs);
            menuDto.setMenuIds(menuIds);
        }
        List<SysMenuTreeListVo> sysMenuVos = CollStreamUtil.toList(menuMapper.selectMenuList(menuDto), sysMenu -> {
            SysMenuTreeListVo sysMenuTreeListVo = new SysMenuTreeListVo();
            BeanUtils.copyProperties(sysMenu, sysMenuTreeListVo);
            return sysMenuTreeListVo;
        });
        return buildMenuListTree(sysMenuVos);
    }

    private List<SysMenuTreeListVo> buildMenuListTree(List<SysMenuTreeListVo> menuVoList) {
        List<SysMenuTreeListVo> menuList = menuVoList.stream().filter((menuVo) -> {
            // 查询一级数据
            return menuVo.getParentId().equals(UserConstants.MENU_PARENT);
        }).map((menuVo) -> {
            // 构造一级数据的children
            menuVo.setLevel(1);
            menuVo.setChildren(getChildrens(menuVo, menuVoList));
            return menuVo;
        }).collect(Collectors.toList());
        return menuList;
    }

    public List<SysMenuTreeListVo> getChildrens(SysMenuTreeListVo root, List<SysMenuTreeListVo> menuList) {
        List<SysMenuTreeListVo> collect = menuList.stream().filter((menuVo) -> {
            return menuVo.getParentId().equals(root.getMenuId());
        }).map((menuVo) -> {
            int level = root.getLevel() + 1;
            menuVo.setLevel(level);
            menuVo.setChildren(getChildrens(menuVo, menuList));
            return menuVo;
        }).collect(Collectors.toList());

        return collect;
    }

    /**
     * 根据菜单ID查询信息
     *
     * @param menuId 菜单ID
     * @return 菜单信息
     */
    @Override
    public SysMenuDetailVo selectMenuById(Long menuId) {
        SysMenu menu = menuMapper.selectById(menuId);
        Assert.isNull(menu, "该菜单/目录不存在");
        SysMenuDetailVo sysMenuDetailVo = new SysMenuDetailVo();
        sysMenuDetailVo.setName(menu.getRouteName());
        BeanUtils.copyProperties(menu, sysMenuDetailVo);
        return sysMenuDetailVo;
    }

    /**
     * 获取菜单下拉树列表
     */
    @Override
    public List<SysMenuTreeSelectVo> treeselect() {
        SysMenuDto sysMenuDto = new SysMenuDto();
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        Set<Long> longs = SecurityUtils.isAdmin(userId) ? null : menuMapper.selectMenuIdsByUserId(userId);
        if (!CollUtil.isEmpty(longs)) {
            List<Long> menuIds = new ArrayList<>(longs);
            sysMenuDto.setMenuIds(menuIds);
        }
        sysMenuDto.setStatus(UserConstants.NORMAL);
        List<SysMenuTreeSelectVo> sysMenuVos = CollStreamUtil.toList(menuMapper.selectMenuList(sysMenuDto),
                sysMenu -> {
                    SysMenuTreeSelectVo sysMenuTreeSelectVo = new SysMenuTreeSelectVo();
                    BeanUtils.copyProperties(sysMenu, sysMenuTreeSelectVo);
                    return sysMenuTreeSelectVo;
                });
        return buildMenuListTree4Select(sysMenuVos);
    }

    private List<SysMenuTreeSelectVo> buildMenuListTree4Select(List<SysMenuTreeSelectVo> menuVoList) {
        List<SysMenuTreeSelectVo> menuList = menuVoList.stream().filter((menuVo) -> {
            // 查询一级数据
            return menuVo.getParentId().equals(UserConstants.MENU_PARENT);
        }).map((menuVo) -> {
            // 构造一级数据的children
            menuVo.setLevel(1);
            menuVo.setChildren(getChildrens4Select(menuVo, menuVoList));
            return menuVo;
        }).collect(Collectors.toList());
        return menuList;
    }

    public List<SysMenuTreeSelectVo> getChildrens4Select(SysMenuTreeSelectVo root, List<SysMenuTreeSelectVo> menuList) {
        List<SysMenuTreeSelectVo> collect = menuList.stream().filter((menuVo) -> {
            return menuVo.getParentId().equals(root.getMenuId());
        }).map((menuVo) -> {
            int level = root.getLevel() + 1;
            menuVo.setLevel(level);
            menuVo.setChildren(getChildrens4Select(menuVo, menuList));
            return menuVo;
        }).collect(Collectors.toList());

        return collect;
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectMenuPermsByUserId(Long userId) {
        List<String> perms = menuMapper.selectMenuPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (ObjectUtil.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

//	/**
//	 * 根据用户ID查询菜单
//	 *
//	 * @param userId 用户名称
//	 * @return 菜单列表
//	 */
//	@Override
//	public List<SysMenu> selectMenuTreeByUserId(Long userId) {
//		List<SysMenu> menus = null;
//		if (SecurityUtils.isAdmin(userId)) {
//			menus = menuMapper.selectMenuTreeAll();
//		} else {
//			menus = menuMapper.selectMenuTreeByUserId(userId);
//		}
//		return getChildPerms(menus, 0);
//	}

    /**
     * 构建前端路由所需要的菜单
     *
     * @param menus 菜单列表
     * @return 路由列表
     */
    @Override
    public List<RouterVo> buildMenus(List<SysMenu> menus) {
        List<RouterVo> routers = new LinkedList<RouterVo>();
        for (SysMenu menu : menus) {
            RouterVo router = new RouterVo();
            router.setHidden("1".equals(menu.getVisible()));
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setAlwaysShow(CharSequenceUtil.equals("0", menu.getAlwaysShow()));
            router.setRedirect(menu.getRedirect());
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(),
                    CharSequenceUtil.equals("1", menu.getIsCache()), menu.getActiveMenu()));
            List<SysMenu> cMenus = menu.getChildren();
            if (!cMenus.isEmpty() && cMenus.size() > 0) {
                router.setAlwaysShow(CharSequenceUtil.equals("0", menu.getAlwaysShow()));
                router.setRedirect(menu.getRedirect());
                router.setChildren(buildMenus(cMenus));
            } else if (isMeunFrame(menu)) {
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                CharSequenceUtil.upperFirst(menu.getPath());
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(),
                        CharSequenceUtil.equals("1", menu.getIsCache()), menu.getActiveMenu()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    /**
     * 是否存在菜单子节点
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    public boolean hasChildByMenuId(Long menuId) {
        QueryWrapper<SysMenu> queryWrapper = new QueryWrapper<SysMenu>();
        queryWrapper.eq("parent_id", menuId);
        int result = menuMapper.selectCount(queryWrapper);
        return result > 0 ? true : false;
    }

    /**
     * 查询菜单使用数量
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    public boolean checkMenuExistRole(Long menuId) {
        QueryWrapper<SysRoleMenu> queryWrapper = new QueryWrapper<SysRoleMenu>();
        queryWrapper.eq("menu_id", menuId);
        int result = roleMenuMapper.selectCount(queryWrapper);
        return result > 0 ? true : false;
    }

    /**
     * 新增保存菜单信息
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public int insertMenu(SysMenu menu) {
        String menuName = menu.getMenuName();
        // 1.校验
        checkMenuCommon(menu);
        //Assert.isTrue(!checkMenuNameUnique(menu), "新增菜单'" + menuName + "'失败，菜单名称已存在");
        Assert.isTrue(
                UserConstants.YES_FRAME.equals(menu.getIsFrame())
                        && !CharSequenceUtil.startWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS),
                "新增菜单'" + menuName + "'失败，地址必须以http(s)://开头");
        return menuMapper.insert(menu);
    }

    /**
     * 修改保存菜单信息
     *
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public int updateMenu(SysMenu menu) {
        String menuName = menu.getMenuName();
        // 1.校验
        checkMenuCommon(menu);
        //Assert.isTrue(!checkMenuNameUnique(menu), "修改菜单'" + menuName + "'失败，菜单名称已存在");
        Assert.isTrue(
                UserConstants.YES_FRAME.equals(menu.getIsFrame())
                        && !CharSequenceUtil.startWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS),
                "修改菜单'" + menuName + "'失败，地址必须以http(s)://开头");
        Assert.isTrue(menu.getMenuId().equals(menu.getParentId()), "修改菜单'" + menuName + "'失败，上级菜单不能选择自己");
        return menuMapper.updateById(menu);
    }

    /*
     * 新增或者更新时传入实体
     */
    public void checkMenuCommon(SysMenu menu) {
        String menuType = menu.getMenuType();
        // 1.校验菜单类型
        Assert.isNotTrue(Arrays.asList("M", "C", "F").contains(menuType), "菜单类型必须为\"M\",\"C\",\"F\"");
        // 2.目录校验
        if (menuType.equals("M")) {
            // 不为空校验
            //目录只能为顶级
            menu.setParentId(0L);
            Assert.isBlank(menu.getIsFrame(), "外链不能为空");
            Assert.isBlank(menu.getVisible(), "显示状态不能为空");
            Assert.isBlank(menu.getStatus(), "菜单状态不能为空");
            // 字符串指定校验
            Assert.isNotTrue(Arrays.asList("0", "1").contains(menu.getIsFrame()), "是否为外链（0否 1是）,请校验");
            Assert.isNotTrue(Arrays.asList("0", "1").contains(menu.getVisible()), "显示状态（0隐藏 1显示）,请校验");
            Assert.isNotTrue(Arrays.asList("0", "1").contains(menu.getStatus()), "菜单状态（0隐藏 1显示）,请校验");
            // 3.菜单校验
        } else if (menuType.equals("C")) {
            // 不为空校验
            Assert.isBlank(menu.getPath(), "路由地址不能为空");
            Assert.isBlank(menu.getIsFrame(), "外链不能为空");
            Assert.isBlank(menu.getVisible(), "显示状态不能为空");
            Assert.isBlank(menu.getStatus(), "菜单状态不能为空");
            Assert.isBlank(menu.getIsCache(), "是否缓存不能为空");
            // 字符串指定校验
            Assert.isNotTrue(Arrays.asList("0", "1").contains(menu.getIsFrame()), "是否为外链（0否 1是）,请校验");
            Assert.isNotTrue(Arrays.asList("0", "1").contains(menu.getVisible()), "显示状态（0隐藏 1显示）,请校验");
            Assert.isNotTrue(Arrays.asList("0", "1").contains(menu.getStatus()), "菜单状态（0隐藏 1显示）,请校验");
            Assert.isNotTrue(Arrays.asList("0", "1").contains(menu.getIsCache()), "是否缓存（0不缓存 1缓存）,请校验");
            // 4.按钮校验（暂时无校验内容）
        } else if (menuType.equals("F")) {

        }
    }

    /**
     * 删除菜单管理信息
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public int deleteMenuById(Long menuId) {
        Assert.isTrue(hasChildByMenuId(menuId), "存在子菜单,不允许删除");
        Assert.isTrue(checkMenuExistRole(menuId), "菜单已分配,不允许删除");
        return menuMapper.deleteById(menuId);
    }

    /**
     * 校验菜单名称是否唯一
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean checkMenuNameUnique(SysMenu menu) {

        boolean result = false;
        String menuName = menu.getMenuName();
        Long menuId = ObjectUtil.isNull(menu.getMenuId()) ? -1L : menu.getMenuId();
        // 1.取得集合
        QueryWrapper<SysMenu> queryWrapper = new QueryWrapper<SysMenu>();
        queryWrapper.eq("menu_name", menuName);
        List<SysMenu> info = menuMapper.selectList(queryWrapper);

        // 2.唯一情况为true
        if (ObjectUtil.isEmpty(info)) {
            result = true;
        } else {
            // 3.不唯一情况下，只有和更新的数据电话号码一样则为true
            if (menuId != -1L) {
                SysMenu menuOld = menuMapper.selectById(menuId);
                Assert.isTrue(menuOld == null, "更新数据不存在，请确认");
                result = info.get(0).getMenuId().equals(menuId) ? true : false;
            }
        }
        return result;
    }

    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(SysMenu menu) {
        String routerName = CharSequenceUtil.upperFirst(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMeunFrame(menu)) {
            routerName = CharSequenceUtil.EMPTY;
        }
        return routerName;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysMenu menu) {
        String routerPath = menu.getPath();
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getParentId().intValue() && UserConstants.TYPE_DIR.equals(menu.getMenuType())
                && UserConstants.NO_FRAME.equals(menu.getIsFrame())) {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMeunFrame(menu)) {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(SysMenu menu) {
        String component = UserConstants.LAYOUT;
        if (ObjectUtil.isNotEmpty(menu.getComponent()) && !isMeunFrame(menu)) {
            component = menu.getComponent();
        }
        return component;
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMeunFrame(SysMenu menu) {
        return menu.getParentId().intValue() == 0 && UserConstants.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame().equals(UserConstants.NO_FRAME);
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list     分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<SysMenu> getChildPerms(List<SysMenu> list, int parentId) {
        List<SysMenu> returnList = new ArrayList<SysMenu>();
        for (Iterator<SysMenu> iterator = list.iterator(); iterator.hasNext(); ) {
            SysMenu t = iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId) {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list
     * @param t
     */
    private void recursionFn(List<SysMenu> list, SysMenu t) {
        // 得到子节点列表
        List<SysMenu> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysMenu tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysMenu> getChildList(List<SysMenu> list, SysMenu t) {
        List<SysMenu> tlist = new ArrayList<SysMenu>();
        Iterator<SysMenu> it = list.iterator();
        while (it.hasNext()) {
            SysMenu n = it.next();
            if (n.getParentId().longValue() == t.getMenuId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysMenu> list, SysMenu t) {
        return getChildList(list, t).size() > 0 ? true : false;
    }

    /**
     * 根据用户ID查询菜单树信息
     *
     * @param userId 用户ID
     * @return RouterVo4M
     */
    @Override
    public List<RouterVo4C> selectRouterVo4MByUserId(Long userId) {

        // 1.构建menuid集合
        Set<Long> menuIds = SecurityUtils.isAdmin(userId) ? null : menuMapper.selectMenuIdsByUserId(userId);

        if (menuIds != null && menuIds.size() == 0) {
            //说明不是admin  但是没有权限
            return new ArrayList<>();
        }

        // 2.查询条件准备
        QueryWrapper<SysMenu> queryWrapper = new QueryWrapper<SysMenu>();
        queryWrapper.in(menuIds != null, "menu_id", menuIds);//说明不是admin登录
        //queryWrapper.in("parent_id", 0);
        //queryWrapper.eq("status", "1");
        // add20210222 by czq,增加排序
        //queryWrapper.orderByAsc("order_num");
        // update20210222 by czq,和前端对接，把目录m也改为了c
        queryWrapper.in("menu_type", Arrays.asList("M", "C"));

        // 3.查询对应的目录并转化
        List<RouterVo4C> vos = CollStreamUtil.toList(menuMapper.selectList(queryWrapper), sysMenu -> {
            RouterVo4C vo = new RouterVo4C();
            vo.setHidden(sysMenu.getVisible() != null && sysMenu.getVisible().equals("1") ? false : true);
            vo.setAlwaysShow(sysMenu.getAlwaysShow() != null && sysMenu.getAlwaysShow().equals("1"));
            MetaVo meta = new MetaVo();
            meta.setParentId(sysMenu.getParentId());
            meta.setMenuId(sysMenu.getMenuId());
            meta.setOrderNum(sysMenu.getOrderNum());
            meta.setActiveMenu(sysMenu.getActiveMenu());
            meta.setIcon(sysMenu.getIcon());
            meta.setNoCache(sysMenu.getIsCache() != null && sysMenu.getIsCache().equals("1"));
            meta.setTitle(sysMenu.getMenuName());
            vo.setName(sysMenu.getRouteName());
            vo.setMeta(meta);
            BeanUtils.copyProperties(sysMenu, vo);
            return vo;
        });

        //4.生成树
        return buildRouterVo4CTree(vos);
    }

    private List<RouterVo4C> buildRouterVo4CTree(List<RouterVo4C> menuVoList) {

        //构造树
        List<RouterVo4C> categoryTree = menuVoList.stream().filter((menuVo) -> {
            //查询一级分类
            return menuVo.getParentId() == 0;
        }).map((menuVo) -> {
            //构造一级分类的children
            menuVo.setChildren(getChildrens(menuVo, menuVoList));
            return menuVo;
        }).sorted((menuVo1, menuVo2) -> {
            return (Integer.valueOf(menuVo1.getOrderNum()) == null ? 0 : Integer.valueOf(menuVo1.getOrderNum())) - (Integer.valueOf(menuVo2.getOrderNum()) == null ? 0 : Integer.valueOf(menuVo2.getOrderNum()));
        }).collect(Collectors.toList());
        return categoryTree;
    }


    /**
     * 递归获取商品分类子类
     *
     * @param root       根目录  获取此菜单下的子类
     * @param menuVoList 全部菜单的集合  大容器
     * @return
     */
    public List<RouterVo4C> getChildrens(RouterVo4C root, List<RouterVo4C> menuVoList) {
        List<RouterVo4C> collect = menuVoList.stream().filter((menuVo) -> {
            return menuVo.getParentId() == root.getMenuId();
        }).map((menuVo) -> {
            menuVo.setChildren(getChildrens(menuVo, menuVoList));
            return menuVo;
        }).sorted((menuVo1, menuVo2) -> {
            return (Integer.valueOf(menuVo1.getOrderNum()) == null ? 0 : Integer.valueOf(menuVo1.getOrderNum())) - (Integer.valueOf(menuVo2.getOrderNum()) == null ? 0 : Integer.valueOf(menuVo2.getOrderNum()));
        }).collect(Collectors.toList());

        return collect;
    }


    public List<RouterVo4C> getChildrens4Select(RouterVo4C root, List<RouterVo4C> menuList) {
        List<RouterVo4C> collect = menuList.stream().filter((menuVo) -> {
            // 1.查询数据,只过滤父节点为menuId的数据
            return menuVo.getParentId().equals(root.getMenuId());
        }).map((menuVo) -> {
            // 2.上诉条件满足的情况下,构造children
            menuVo.setChildren(getChildrens4Select(menuVo, menuList));
            return menuVo;
        }).collect(Collectors.toList());

        return collect;
    }

}
